package com.oocl.view;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.text.ParseException;
import java.util.Date;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

import org.json.JSONException;
import org.json.JSONObject;
import org.xml.sax.InputSource;

import com.oocl.constant.LogLevel;
import com.oocl.constant.ProtocolType;
import com.oocl.pojo.Protocol;
import com.oocl.util.JsonUtil;
import com.oocl.util.LogUtil;
import com.oocl.util.ResourceReleaser;

@SuppressWarnings("serial")
public class Login extends JFrame implements ActionListener {
	
	private JLabel titleJLabel;
	private JTextField nameTf;
	private JPasswordField  psdPf;
	private JButton loginBtn;
	private JButton registerBtn;
	private JLabel usernameLabel;//login
	private JLabel passwordLabel;//password
	private JLabel tips;
	
	private String username;
	public static void main(String[] args) {
		new Login();
	}
	public Login() {
		this.setSize(400, 260);
		this.setResizable(false);//窗体是否可以调整大小
		this.setLocationRelativeTo(null);//位于屏幕中央
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//用户单击窗口的关闭按钮时程序执行的操作
		init();
		addEvent();
		this.setVisible(true);
		
	}

	private void init(){
		this.setLayout(null);
		nameTf=new JTextField();
		psdPf=new JPasswordField();
		loginBtn=new JButton("login");
		registerBtn=new JButton("register");
		titleJLabel=new JLabel("欢迎登录");
		usernameLabel=new JLabel("username:");
		passwordLabel=new JLabel("password:");
		tips=new JLabel();
		
		titleJLabel.setBounds(160,2,230,50);
		titleJLabel.setFont(new Font("宋体", Font.BOLD, 20));
		nameTf.setBounds(120, 50, 230, 40);
		psdPf.setBounds(120, 100, 230, 40);
		loginBtn.setBounds(120, 160, 90, 40);
		registerBtn.setBounds(260, 160, 90, 40);
		usernameLabel.setBounds(40,50, 70, 40);
		passwordLabel.setBounds(40,100, 70, 40);
		tips.setBounds(80, 130, 230, 40);
		tips.setForeground(Color.red);

		this.add(titleJLabel);
		this.add(nameTf);
		this.add(psdPf);
		this.add(loginBtn);
		this.add(registerBtn);
		this.add(usernameLabel);
		this.add(passwordLabel);
		this.add(tips);
	}
	private void addEvent(){
		loginBtn.addActionListener(this);
		registerBtn.addActionListener(new ActionListener() {
			@Override
			
			public void actionPerformed(ActionEvent e) {
				Login.this.setEnabled(false);
				Login.this.setVisible(false);
				new Register();
			}
		});
	}
	
	@Override
	public void actionPerformed(ActionEvent e) {
		String psd = new String(psdPf.getPassword());
		if("".equals(nameTf.getText().trim()) || "".equals(psd.trim())){
			tips.setText("username or password can not be empty!");
		}else {
			username = nameTf.getText();
			Socket socket = null;
			BufferedReader in = null;
			PrintWriter out = null;
			try {
				//10.222.29.201
				socket = new Socket("10.222.29.201", 7777);
				out = new PrintWriter(socket.getOutputStream());
				in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
				Protocol protocol = new Protocol();
				protocol.setType(ProtocolType.LOGIN);
				protocol.setFrom(username);
				protocol.setContent(psd);
				protocol.setTime(new Date());
				JSONObject json = JsonUtil.toJsonObject(protocol);
				out.println(json.toString());
				out.flush();
				
				String line = in.readLine();
				JSONObject json1 = new JSONObject(line.trim());
				Protocol pro1 = JsonUtil.toProtocol(json1);
				if(pro1.getType()==ProtocolType.LOGIN_SUCCESS){	//登录成功连接聊天服务器
					LogUtil.log("login secess", LogLevel.INFO);
					Socket socket1 = new Socket("10.222.29.201", 8888);
					PrintWriter out1 = new PrintWriter(socket1.getOutputStream());
					BufferedReader in1 = new BufferedReader(new InputStreamReader(socket1.getInputStream()));
					
					//加载在线用户列表
					Protocol pro2 = new Protocol();
					pro2.setType(ProtocolType.LOAD_USERS);
					pro2.setFrom(username);
					pro2.setTime(new Date());
					out1.println(JsonUtil.toJsonObject(pro2).toString());
					out1.flush();
					String line1 = in1.readLine();
					System.out.println(line1);
					Protocol pro3 = JsonUtil.toProtocol(new JSONObject(line1.trim()));
					if(pro3.getType()==ProtocolType.LOAD_USERS){
						new ChatFrame(socket1, in1, out1, username,pro3.getOnlineUsers());
						Login.this.setEnabled(false);
						Login.this.setVisible(false);
					}
				}else {
					LogUtil.log("login fail", LogLevel.INFO);
					tips.setText(pro1.getContent());
				}
			} catch (UnknownHostException e1) {
				LogUtil.log("UnknownHostException!"+e1.getMessage(), LogLevel.ERROR);
				JOptionPane.showMessageDialog(null, "找不到服务器连接", "Tip", JOptionPane.ERROR_MESSAGE);
				ResourceReleaser.release(out, in, socket);
			} catch (IOException e1) {
				LogUtil.log("IOException!"+e1.getMessage(), LogLevel.ERROR);
				JOptionPane.showMessageDialog(null, "找不到服务器连接", "Tip", JOptionPane.ERROR_MESSAGE);
				ResourceReleaser.release(out, in, socket);
			} catch (JSONException e1) {
				e1.printStackTrace();
			} catch (ParseException e1) {
				e1.printStackTrace();
			}
		}
		
	}
	
}
